from moviepy.editor import AudioFileClip
import os

#生成MP3文件，MP3文件会放到视频目录下的mp3Dir文件夹下
def getMP3(filePath):
    print(filePath)
    #文件名，不带后缀
    filename = os.path.basename(filePath).split(".")[0]+ ".mp3"
    dirName = os.path.dirname(filePath)

    mp3DirName = os.path.join(dirName,"mp3Dir")
    if not os.path.exists(mp3DirName):
        os.makedirs(mp3DirName)
    mp3 = os.path.join(mp3DirName,filename)

    my_audio_clip = AudioFileClip(filePath)
    my_audio_clip.write_audiofile(mp3)



# 返回文件路径list
def findAllFile(base):
    for root, ds, fs in os.walk(base):
        for f in fs:
            if f.endswith('.mp4'):
                fullname = os.path.join(root, f)
                yield fullname


def work(path):
    if os.path.isdir(path):
        files = findAllFile(path)
        for file in files:
            getMP3(file)
    if os.path.isfile(path):
        file = path
        getMP3(file)

if __name__ == '__main__':
    path = "D:\\win-videos\\TestVideo\\test.mp4"
    work(path)



